import random
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from meiduo_mall.libs.yuntongxun.sms import CCP
from verifications import constants



# Create your views here.


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    def get(self, request, mobile):
        """
        获取短信验证码
        1 获取随机生成6位数作为短信验证码
        2 在redis中存储短信验证码内容 以‘sms_<mobile>为key’，以验证码内容为value
        3 使用云通讯给‘mobile’发送短信
        4 返回应答，短信发送成功
        :param request:
        :param mobile:
        :return:
        """
        #判断给‘mobile’ 60s之内是否发送过短信
        redis_coon = get_redis_connection('verify_codes')

        send_flag = redis_coon.get('send_flag_%s' % mobile) # None

        if send_flag:
            # 60s之内给‘mobile’ 发送过短信
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_403_FORBIDDEN)

        #1 获取随机生成6位数作为短信验证码
        sms_code = '%06d' % random.randint(0, 999999)


        # 2 在redis中存储短信验证码内容 以‘sms_<mobile>为key’，以验证码内容为value

        # 创建redis管道对象
        pl = redis_coon.pipeline()

        #想管道中添加命令
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_COOD_INTERVAL, 1)

        #一次性执行管道中所有的命令
        pl.execute()

        redis_coon.setex('<sms_%s>' %mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        redis_coon.setex('send_flag_%s' %mobile, constants.SEND_SMS_COOD_INTERVAL, 1)

        # # 3 使用云通讯给‘mobile’发送短信
        # expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        # try:
        #     res = CCP().send_template_sms(mobile, [sms_code, expires], constants.SEND_SMS_TEMP_ID)
        # except Exception as e:
        #     return Response({'message': '验证码发送失败'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        #
        # if res != 0:
        #     # 短信发送失败
        #     return Response({'message': '验证码发送失败'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 4 返回应答，短信发送成功
        return Response({'message': 'ok'})

